package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CacheClient cacheClient;
    @Override
    public Result queryById(Long id) {
        //互斥锁
//        Shop shop = queryWithMutex(id);
        //逻辑过期
//        Shop shop = queryWithLogicalExpire(id);
        //工具类 缓存穿透
        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, 20L, TimeUnit.SECONDS);
        //工具类 缓存击穿——逻辑过期
//        Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, LOCK_SHOP_KEY,id, Shop.class, this::getById, 10L, TimeUnit.SECONDS);

         if (shop == null) {
            return Result.fail("未查到指定的商户信息");
        }
        return Result.ok(shop);
    }
    //互斥锁解决缓存穿透问题
    public Shop queryWithMutex(Long id) {
        //1从redis中查询shop缓存
        String cacheShop = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        //2查询到了，直接返回
        if (StrUtil.isNotBlank(cacheShop)) {
            //不为null，不为""，不为换行符等，必须为实际的字符
            Shop shop = JSONUtil.toBean(cacheShop, Shop.class);
            return shop;
        }
        //为空对象，即""的情况
        if (cacheShop!=null){
            //类型转换
            //ignoreError忽略在转换过程中遇到的错误。如果 JSON 字符串中的某个字段在 Java Bean 中不存在，或者字段值的类型无法正确转换
            return null;
        }
        //3没查询到，查询数据库
        Shop shop = null;
        try {
            //先获取锁
            boolean flag = tryLock(LOCK_SHOP_KEY + id);
            //获取失败，休眠
            if (!flag) {
                Thread.sleep(50);
                //休眠完了再次发起请求
                return queryWithMutex(id);
            }
            shop = getById(id);
            //模拟数据库耗时操作
            Thread.sleep(200);
            //4数据库也没查到，返回fail
            if (shop == null) {
                //存入空对象
                stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "",CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //5数据库查到了，结果存放在redis中
            String jsonStr = JSONUtil.toJsonStr(shop);
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, jsonStr,CACHE_SHOP_TTL, TimeUnit.MINUTES);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            unLock(LOCK_SHOP_KEY + id);
        }
        //6返回结果
        return shop;
    }
    //使用redis模拟锁
    public boolean tryLock(String key){
        //尝试set
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        //就可能出现包装类的情况
        return BooleanUtil.isTrue(flag);
    }
    public void unLock(String key){
        //尝试delete
        stringRedisTemplate.delete(LOCK_SHOP_KEY+key);
        return ;
    }
    //逻辑过期解决缓存穿透问题
    //线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public Shop queryWithLogicalExpire(Long id) {
        //1从redis中查询shop缓存
        String cacheShop = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        //2没查到
        //默认只要存在一定能查到，只不过可能过期了而已
        if (StrUtil.isBlank(cacheShop)) {
            //不为null，不为""，不为换行符等，必须为实际的字符
            return null;
        }

        //3查询到
        //4判断是否过期
        RedisData redisData = JSONUtil.toBean(cacheShop, RedisData.class);
        Object data = redisData.getData();
        LocalDateTime expireTime = redisData.getExpireTime();
        JSONObject jsonObject =(JSONObject) data;
        Shop shop = JSONUtil.toBean(jsonObject, Shop.class);
        //判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //没过期
            return shop;
        }
        //过期
        //获取锁
        String lockKey = LOCK_SHOP_KEY + id;
        //获取成功
        boolean flag = tryLock(lockKey);
        if (flag) {
            //开启独立线程
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    this.saveShop2Redis(id,20L);
                    //释放锁
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(lockKey);
                }
            });
        }

        //获取失败
        //返回结果
        return shop;
    }
    public void saveShop2Redis(Long id,Long expireSeconds) throws InterruptedException {
        Shop shop = getById(id);
        //模拟数据库耗时
        Thread.sleep(200);
        RedisData redisData = RedisData.builder()
                .data(shop)
                .expireTime(LocalDateTime.now().plusSeconds(expireSeconds))
                .build();

        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id, JSONUtil.toJsonStr(redisData));
    }
    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        //1操作数据库
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("shop id is null");
        }
        updateById(shop);
        //2删除redis缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //1判断是否基于距离
        if (x==null||y==null){
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        //2计算分页参数
        int from =(current-1)*SystemConstants.DEFAULT_PAGE_SIZE;
        int end =(current)*SystemConstants.DEFAULT_PAGE_SIZE;
        //3查询redis中指定类别的记录
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .radius(SHOP_GEO_KEY + typeId, new Circle(new Point(x, y), new Distance(5000, RedisGeoCommands.DistanceUnit.METERS)), RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs()
                        .includeDistance().limit(end));
        if (results==null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> geoResults = results.getContent();
        if (geoResults.size()<=from){
            return Result.ok(Collections.emptyList());
        }
        //过滤
        //4遍历shoplist，
        List<Long> ids = new ArrayList<>(geoResults.size());
        HashMap<Long, Distance> map = new HashMap<>(geoResults.size());
        geoResults.stream().skip(from).forEach(geoResult->{
            String shopId = geoResult.getContent().getName();
            Distance distance = geoResult.getDistance();
            ids.add(Long.valueOf(shopId));
            map.put(Long.valueOf(shopId), distance);
        });

        //查询shopId对应的shop
        String strFormat = StrUtil.join(",", ids);
        List<Shop> shopList = query().in("id", ids).last("ORDER BY FIELD(id," + strFormat + ")").list().stream().map(shop -> {
            //为其添加distance
            return shop.setDistance(map.get(shop.getId()).getValue());
        }).collect(Collectors.toList());
        return Result.ok(shopList);
    }
}
